<template>
  <div class="articles">

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <div v-show="!pageLoading">
      <div v-show="!showList"  >
        <button class="btn btn-default fixed-menu" v-if="float=='left'"  style="left: 1em" @click="showList=!showList"><i class="glyphicon glyphicon-align-justify"></i></button>
        <button class="btn btn-default fixed-menu" v-else  style="right: 1em" @click="showList=!showList"><i class="glyphicon glyphicon-align-justify"></i></button>
      </div>
      <div class="list" :style="{float:float}"   v-infinite-scroll="getList"
           infinite-scroll-disabled="loadingList"
           infinite-scroll-distance="10" v-show="showList" :class="{
           'list-show':showList
         }">
        <!--<div class="list" :style="{float:float}"  >-->
        <form  class="form-inline">
          <button class="btn btn-default hidden-xs" @click="showList=!showList"><i class="glyphicon glyphicon-align-justify"></i></button>
          <a @click="float='right'" v-if="float == 'left'" class="btn btn-default hidden-xs">→</a>
          <a @click="float='left'" class="btn btn-default hidden-xs" v-else  >←</a>
          <select v-model.number="index" class="form-control">
            <option value="1">综合</option>
            <option value="2">工作情感</option>
            <option value="3">漫画小说</option>
            <option value="4">游戏</option>
            <option value="5">动漫文化</option>
          </select>
        </form>
        <div class="list-items">
          <div  v-for="item  in datalist" :key="item.contentId" class="list-item" >
            <a class="title-box" @click="toArticle(item.contentId)" >
              <span class="title" v-html="item.title"></span>
              <span class="date">{{getDateDiff(item.releaseDate)}}</span>
            </a>
            <div class="desc" v-html="item.description">
            </div>
            <div class="info">
              <span class="info-item comments" title="Views">浏览:{{item.views}}</span>
              <span class="info-item comments" title="Comments">评论:{{item.comments}}</span>
              <span class="info-item author" title="Author">UP:{{item.user.username}}</span>
            </div>
          </div>
        </div>
        <span class="btn center-block" @click="getList" v-show="loadingList">加载.....</span>

      </div>
      <div class="article hidden-xs" @scroll="handleScroll">
        <p class="h3">{{article.title}}</p>
        <div class="content" v-html="article.article.content">
        </div>
        <div class="author-info ">
        <span class="col-md-6 text-left">
        <p class="">标签</p>
        <span class="tag bg-info" v-for="tag in article.tags" v-text="tag" ></span>
        </span>
          <span class="col-md-6 text-right">
        <img :src="article.owner.avatar"  class="avatar up-icon">
        <span class="h5 ">UP:{{article.owner.name}}</span>
        </span>
          <div class="clearfix"></div>
        </div>
        <p class="comments-title">评论列表</p>
        <div class="comments"  v-infinite-scroll="loadMoreComments"
             infinite-scroll-disabled="loading"
             infinite-scroll-distance="10" >
          <div class="comment-row" v-for="(comment,index) in commentList" :key="comment.cid" :data-cid="comment.cid">
            <div v-show="comment.quoteId!=quoteMap['final'+comment.cid]">
              <comment  v-if="comment.quoteId>0" :quoteMap="quoteMap" :currentId="comment.cid" :comment="getQuote(comment)" :list="comments">
              </comment>
            </div>
            <p class="collapse" v-show="comment.quoteId==quoteMap['final'+comment.cid]"  @click="showCollapse">[重复引用已隐藏]</p>
            <img class="avatar" :src="comment.userImg" >
            <div class="comment-box">
              <a class="username" :class="{upname:comment.userName==upName}" :href="`http://m.acfun.cn/details?upid=${comment.userID}`"> #{{comment.count}} {{comment.userName}}</a>
              <div class="comment-info" v-html="comment.content"></div>
            </div>
          </div>
        </div>
        <div class="btns-box" :style="{right:float=='right'?'calc(30vw + 10px)':'10px'}">
          <img class="operate-btn" v-if="showTop" @click="top" src="../assets/top.png">
          <div @click="toComments">
            <img class="operate-btn"  src="../assets/comments.png">
            <mt-badge size="small"  class="comment-count">{{totalCount}}</mt-badge>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import fetch from '../utils/fetch'
  import comment from  './comment.vue'
  import { mapGetters } from 'vuex';
  import Cookies from 'js-cookie'
  import { Indicator } from 'mint-ui';

  const EmojiUrl = 'http://cdn.aixifan.com/acfun-H5/public';
  let apiurl = 'acfun/contents?pageNo={pageNo}';

  export default {
    components:{
      comment:comment
    },
    data () {
      return {
        pageLoading:true,
        article:{article:{},owner:{},tags:[]},
        articleId:0,
        float:Cookies.get('float')||'left',
        comments:{},
        commentList:[],
        datalist:[],
        allCommentIds:[],
        quoteMap:{},
        pageNo:1,
        upName:'',
        loading:false,
        showList:true,
        pageSize:30,
        totalPage:0,
        totalCount:0,
        loadingList:true,
        listPageNo:[0,0,0,0,0],
        index:Cookies.get('index')||1,
        channelIds:0,
        showTop:false,
        lastContentId:[0,0,0,0,0]
      }
    },
    created(){
      let index = location.host.indexOf('gakki')>=0?1:0;
      this.$store.dispatch('switchUrl',index);
      this.handleIndex(parseInt(this.index));
    },
    computed: {
      ...mapGetters([
        'list',
        'list2',
        'list3',
        'list5',
        'list4',
        'url'
      ])
    },
    watch:{
      showList(val){
        if(!val){
          document.querySelector('.article').style.width='100%'
        }else {
          document.querySelector('.article').style.width='70%'
        }
      },
      index(val){
        this.handleIndex(val);
        Cookies.set('index',val)
      },
      float(val){
        Cookies.set('float',val)
      }
    },
    methods:{
      isMobile(){
        let mobile = false;
        var ele =  document.querySelector('.hidden-xs');
        let style = window.getComputedStyle(ele)
        if(style.display=='none'){
          mobile = true;
        }
        return mobile;
      },
      handleIndex(ind){
        switch (parseInt(ind)) {
          case 1:
            this.channelIds = 110
            this.datalist = this.list
            break
          case 2:
            this.channelIds = 73
            this.datalist = this.list2
            break
          case 3:
            this.channelIds = 75
            this.datalist = this.list3
            break
          case 4:
            this.channelIds = 164
            this.datalist = this.list4
            break
          case 5:
            this.channelIds = 74
            this.datalist = this.list5
            break
        }
        if(this.datalist.length==0){
          this.getList()
        }else {
          this.pageLoading = false;
        }
      },
      handleScroll(){
        const ele = document.querySelector('.article')
        if(ele.scrollTop>window.innerHeight){
          this.showTop = true
        }else {
          this.showTop = false
        }
      },
      getDateDiff(dateTimeStamp){
        let result;
        var minute = 1000 * 60;
        var hour = minute * 60;
        var day = hour * 24;
        var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime();
        var diffValue = now - dateTimeStamp;
        if(diffValue < 0){return;}
        var monthC = diffValue/month;
        var weekC = diffValue/(7*day);
        var dayC = diffValue/day;
        var hourC = diffValue/hour;
        var minC = diffValue/minute;
        if(monthC >= 1){
          result = "" + parseInt(monthC) + "月前";
        }
        else if(weekC >= 1){
          result = "" + parseInt(weekC) + "周前";
        }
        else if(dayC >= 1){
          result = ""+ parseInt(dayC) +"天前";
        }
        else if(hourC >= 1){
          result = ""+ parseInt(hourC) +"小时前";
        }
        else if(minC >= 1){
          result = ""+ parseInt(minC) +"分钟前";
        }else
          result = "刚刚";
        return result;
      },
      getList(){
        Indicator.open('加载中...');
        let pageNo = this.listPageNo[this.index-1];
        pageNo++
        this.listPageNo[this.index-1] = pageNo;
        let url = this.url+apiurl.replace('{pageNo}',pageNo)
        if(this.channelIds>0){
          url+=`&channelIds=${this.channelIds}`
        }
        this.loadingList = true;
        fetch.get(url).then(response=>{
          let datalist = response.data.data?response.data.data.list:[];
          datalist.forEach((e,ind)=>{
            if(ind==0&&pageNo==1){
              this.articleId = e.contentId;
              this.getArticle()
            }
            if(this.lastContentId[this.index-1]==0||e.contentId<this.lastContentId[this.index-1]){
              this.$store.dispatch('addContent',{content:e,index:parseInt(this.index)}).then(()=>{

              })
            }
          });
          if(datalist.length>0){
            this.lastContentId[this.index-1] = datalist[datalist.length-1].contentId;
          }
          this.loadingList = false;
          this.pageLoading = false;
          Indicator.close();
        }).catch(error=>{
          console.log(error)
        })
      },
      toArticle(id){
        this.articleId = id;
        if(this.isMobile()){
          this.$router.push(`/article/${id}`)
        }else {
          this.getArticle();
        }
      },
      showCollapse(e){
        const ele = e.target;
        const comments = ele.previousElementSibling;
        ele.style.display = 'none'
        comments.style.display = 'block'
      },
      getArticle(){
        fetch.get(`${this.url}acfun/contents/${this.articleId}`).then(res=>{
          this.article = res.data.data;
          this.upName = this.article.owner.name;
          this.pageNo = 1 ;
          this.comments={}
          this.commentList=[]
          this.allCommentIds=[]
          this.quoteMap ={}
          this.getComments();
          this.top()
          this.$nextTick(()=>{
            var eles = document.querySelectorAll('.content img');
            eles.forEach(e=>{
              if(e.className!='emotion'&&e.className!='img-emot-ac'){
                e.removeAttribute('height')
                e.removeAttribute('style')
                e.style.maxWidth='95%'
                e.style.margin='0 auto'
                e.style.display='block'
                while(e.parentNode.classList['value']!='content'){
                  e.parentNode.removeAttribute('style')
                  e = e.parentNode;
                }
              }
              e.style.verticalAlign='baseline'
            })
          })
        }).catch(err=>{
          console.log(err)
        })
      },
      getComment(id){
        return this.comments['c'+id];
      },
      getQuote(comment){
        let res = this.getComment(comment.quoteId);
        return res;
      },
      getComments(){
        let url = `${this.url}acfun/contents/${this.articleId}/comments`
        if(this.pageNo>1){
          url += `?pageNo=${this.pageNo}`
        }
        fetch.get(url).then(res=>{
          if(typeof res.data =='string'){
            this.loading = false;
            let data = JSON.parse(res.data.replace('system.tv=',""))
            let comments = data.data.commentContentArr;
            this.totalPage = data.data.totalPage;
            this.totalCount = data.data.totalCount;
            for(let v in comments){
              let ele  = comments[v]
              ele.content = -1 === ele.content.search(/(?:\[[^\]]*?\[)|(?:\][^\[]*?\])/) ? ele.content : ele.content.replace(/\[.*?\]/g, "").replace(/\[|\]/g, ""),
                ele.content = ele.content.replace(/&amp;/g, "&").replace(/&nbsp;/g, " ").replace(/&#39;/g, "'").replace(/(&quot;|&#34;)/g, '"').replace(/&gt;/g, ">").replace(/&lt;/g, "<").replace(/<br\s?\/?>/g, "").replace(/((\s|&nbsp;)*\r?\n){3,}/g, "\r\n\r\n").replace(/^((\s|&nbsp;)*\r?\n)+/g, "").replace(/((\s|&nbsp;)*\r?\n)+$/g, ""),
                window.ubb2html ? (ele.content = window.ubb2html(ele.content),
                  ele.content = ele.content.replace(/\[p\]/g, "<p>").replace(/\[\/p\]/g, "</p>")) : ele.content ,
                ele.content = ele.content.replace(/\[ac\=(\S+?)\](\S+?)\[\/ac\]/g, '<a class="ac title btn" data-aid="$1" href="/v/ac$1" target="_blank"><i class="icon icon-play-circle"></i>$2</a>').replace(/\[aa\=(\S+?)\](\S+?)\[\/aa\]/g, '<a class="aa btn" href="/a/aa$1" target="_blank" title="该链接通向AcFun合辑"><i class="icon icon-list"></i>$2</a>').replace(/\[sm\=(\S+?)\](\S+?)\[\/sm\]/g, '<a class="sm btn" href="http://www.nicovideo.jp/watch/sm$1" target="_blank" title="该链接通向ニコニコ动画"><i class="icon icon-film"></i>$2</a>').replace(/\[email\](\S+?)\[\/email\]/g, '<a class="email btn" href="mailto:$1" target="_blank" title="点击以发送邮件"><i class="icon icon-envelope"></i>$1</a>').replace(/\[wiki\=(\S+?)\](\S+?)\[\/wiki\]/g, '<a class="wiki btn" href="http://wiki.acfun.cn/index.php/$1" target="_blank" title="该链接通向AC百科"><i class="icon icon-tag"></i>$2</a>');
              var a = new Date;
              3 == a.getMonth() && 1 == a.getDate() ? ele.content = ele.content.replace(/\[emot\=(\S+?)\,(\S+?)\/\]/g, '<img class="emotion flipy" style="max-width: 60px;max-height: 60px;vertical-align: baseline" src="' + EmojiUrl + '/umeditor/dialogs/emotion/images/$1/$2.gif">') : ele.content = ele.content.replace(/\[emot\=(\S+?)\,(\S+?)\/\]/g, '<img class="emotion" style="max-width: 60px;max-height: 60px;vertical-align: baseline" src="http://cdn.aixifan.com/dotnet/20130418/umeditor/dialogs/emotion/images/$1/$2.gif">'),
                ele.content = ele.content.replace(/\[acimg\](\S+?)\[\/acimg\]/g, '<img src="$1"/>').replace(/\[acimg\=(\S+?)\](\S+?)\[\/acimg\]/g, '<img src="$2"/>'),
                ele.content = ele.content.replace(/\[img\](\S+?)\[\/img\]/g, '<a class="thumb" href="$1" target="_blank" title="点击以浏览图像"><img class="preview" src="$1"></a>'),
                ele.content = ele.content.replace(/\[at\]([\s\S]+?)\[\/at\]/g, '<a class="name" target="_blank" href="http://www.acfun.cn/member/findUser.aspx?userName=$1">@$1</a>').replace(/\[\/?back.*?\]/g, "").replace(/\[username\]([\s\S]+?)\[\/username\]/g, '<a  class="name" target="_blank" href="/member/findUser.aspx?userName=$1">$1</a>').replace(/\[.*?\]/g, "").replace(/([\s\W\_])[o|O][n|N]\w+?\s*?\=/g, "$1data-event="),
                ele.content = ele.content.trim(),
                ele.content = ele.content.replace(/&amp;/g, "&").replace(/&#91;/g, "[").replace(/&#93;/g, "]")
              this.comments[v] = ele;
            }
            const commentList = [];
            data.data.commentList.forEach((v,index)=>{
              let obj = this.getComment(v);
              this.allCommentIds.push(obj.cid)
              let com = obj;
              for(let ind=1024;ind>0 && com && com.quoteId>0 && this.getComment(com.quoteId);ind--){
                if(this.allCommentIds.indexOf(com.quoteId)>=0){
                  this.quoteMap['final'+obj.cid]=com.quoteId
                  break;
                }
                this.allCommentIds.push(com.quoteId)
                com = this.getComment(com.quoteId)
              }
              commentList.push(obj);
            });
            commentList.forEach(v=>{
              this.commentList.push(v);
            })
          }
        }).catch(err=>{
          console.log(err)
        })
      },
      loadMoreComments(){
        if(this.pageNo<this.totalPage){
          this.pageNo++
          this.loading = true;
          this.getComments()
        }
      },
      toComments(){
        const dest = document.querySelector('.comments-title').offsetTop;
        const ele = document.querySelector('.article')
        ele.scroll({
          behavior: 'smooth',
          left: 0,
          top: dest-200
        });
      },
      top(){
        const ele = document.querySelector('.article')
        ele.scroll({
          behavior: 'smooth',
          left: 0,
          top: 0
        });
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .fixed-menu{
    margin: 1em;
    position: fixed;
    z-index: 5;
  }
  [v-cloak]{
    display: none;
  }
  .upname:after{
    content: '[阿婆主]';
  }
  .upname:hover{
    font-weight: bold;
  }
  .author-info{
    padding: 20px 10px;
    border: thin solid #ccc;
    border-radius: 10px;
    margin: 20px 0;
  }
  .tag{
    margin-right: 10px;
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
  }

  .articles{
    height: 100%;
    overflow: hidden;
  }
  .list{
    width: 30%;
    height: 100vh;
    overflow: auto;
    text-align: left;
  }
  .list-items{
    padding: 60px 1em 1em;
  }
  .form-inline{
    position: fixed;
    padding: 5px 10px;
    background: rgba(255,255,255,.9);
  }
  @keyframes list-fade {
    from{
      opacity: 0;
      width: 0;
    }
    to{
      opacity: 1;
      width: 30%;
    }
  }

  .article{
    width: 70%;
    height: 100vh;
    overflow: auto;
    float: right;
    padding: 0 1em 1em;
    position: relative;
  }
  .list-item{
    padding: 10px 0;
    border-bottom: thin solid #cccccc;
  }
  .title-box{
    padding-top: 5px;
    display: flex;
    text-decoration: none;
  }
  .title{
    flex-grow: 1;
    padding-right: 10px;
  }
  .date{
    text-align: right;
    color: #ccc;
    font-size: 0.8em;
    flex-shrink: 0;
  }
  .desc{
    font-size: 0.8em;
    padding: 5px 0;
  }
  .info{
    display: flex;
    font-size: 0.8em;
  }
  .info-item{
    align-self: flex-end;
    flex: 1;
  }

  .title{
    cursor: pointer;
  }
  .title,.comments-title{
    font-size: 1.1em;
    font-weight: bold;
  }
  .comment-count{
    position: absolute;
    bottom: 10px;right: 10px;
  }
  .btns-box{
    position: fixed;
    bottom: 20px;
    right: 20px;
    padding: 10px;
    background: transparent;
  }
  .operate-btn{
    display: block;
    cursor: pointer;
  }
  .comments-title{
    text-align: left;
  }
  .collapse{
    text-align: center;
    padding: 5px 0;
    border: thin solid #ccc;
    margin: 0;
    display: block;
    cursor: pointer;
  }
  .username{
    color: #888;
    padding: 6px;
  }
  .avatar {
    background-color: #eee;
    width: 45px;
    height: 45px;
    border-radius: 5px;
    margin-top: 5px;
    vertical-align: top;
  }
  .up-icon{
    vertical-align: text-bottom;
  }
  .comment-box{
    display: inline-block;
    width: calc(100% - 60px);
  }
  .content,.comments{
    text-align: left;
  }
  .content{
    word-break: break-all;
    overflow-x: hidden;
  }
  .comment-row{
    border: 1px solid #ccc;
    padding: 2px 3px 5px;
    font-size: 12px;
  }
  .comment-info{
    padding: 6px;
    color: #666;
    word-break: break-all;
  }
  .comment-row:not(:first-child){
    margin-top: 5px;
  }
  @media (max-width: 750px) {
    .list{
      width: 100%;
      height: auto;
      overflow: inherit;
    }
    .form-inline{
      width: 100%;
    }
  }
  @media (min-width: 750px) {
    .list-show{
      animation: list-fade 1s ;
      transform-origin: left bottom ;
    }
    .form-inline{
      width: 29%;
    }
  }

</style>
